<template>
  <div class="download-requests-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>下载请求管理</span>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-filter-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="申请人">
            <el-input 
              v-model="searchForm.applicant" 
              placeholder="请输入申请人姓名"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="请求状态">
            <el-select 
              v-model="searchForm.request_status" 
              placeholder="请选择请求状态"
              clearable
            >
              <el-option label="待审核" value="待审核"></el-option>
              <el-option label="已批准" value="已批准"></el-option>
              <el-option label="已拒绝" value="已拒绝"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据表格 -->
      <el-table 
        v-loading="loading" 
        :data="paginatedRequests" 
        style="width: 100%"
        border
      >
        <el-table-column prop="request_id" label="请求ID" width="100" />
        <el-table-column prop="user_id" label="用户ID" width="100" />
        <el-table-column prop="applicant" label="申请人" width="120" />
        <el-table-column prop="request_content" label="请求内容" min-width="200">
          <template #default="{ row }">
            <div class="request-content" @click="viewRequestDetail(row.request_id)">
              {{ formatRequestContent(row.request_content) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="request_reason" label="申请原因" width="200">
          <template #default="{ row }">
            <el-tooltip :content="row.request_reason" placement="top">
              <div class="reason-text">{{ truncateText(row.request_reason, 30) }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="request_time" label="申请时间" width="180" />
        <el-table-column prop="request_status" label="请求状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusType(row.request_status)" 
              effect="plain"
            >
              {{ row.request_status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reviewer" label="审核人" width="120" />
        <el-table-column prop="review_time" label="审核时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <template v-if="row.请求状态 === '待审核'">
              <el-button type="success" size="small" @click="approveRequest(row)">批准</el-button>
              <el-button type="danger" size="small" @click="rejectRequest(row)">拒绝</el-button>
            </template>
            <el-button size="small" @click="viewRequestDetail(row.request_id)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredRequests.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 查看请求详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="下载请求详情"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="请求ID">{{ currentRequest.request_id }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentRequest.user_id }}</el-descriptions-item>
        <el-descriptions-item label="申请人">{{ currentRequest.applicant }}</el-descriptions-item>
        <el-descriptions-item label="请求内容">
          <div class="detail-content">{{ currentRequest.request_content }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="申请原因">{{ currentRequest.request_reason }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ currentRequest.request_time }}</el-descriptions-item>
        <el-descriptions-item label="请求状态">
          <el-tag :type="getStatusType(currentRequest.request_status)" effect="plain">{{ currentRequest.request_status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核意见">{{ currentRequest.review_comments || '-' }}</el-descriptions-item>
        <el-descriptions-item label="审核人">{{ currentRequest.reviewer || '-' }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ currentRequest.review_time || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    
    <!-- 审核对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      :title="reviewType === 'approve' ? '批准请求' : '拒绝请求'"
      width="500px"
    >
      <el-form :model="reviewForm" ref="reviewFormRef" label-width="100px">
        <el-form-item label="审核意见" prop="review_comments">
          <el-input 
            v-model="reviewForm.review_comments" 
            placeholder="请输入审核意见"
            type="textarea"
            rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button 
            :type="reviewType === 'approve' ? 'success' : 'danger'" 
            @click="submitReview"
          >
            确认{{ reviewType === 'approve' ? '批准' : '拒绝' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { downloadAPI } from '../api'

// 状态数据
const loading = ref(false)
const requests = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const searchForm = ref({
  applicant: '',
  request_status: ''
})
const dateRange = ref([])

// 详情对话框相关
const detailDialogVisible = ref(false)
const currentRequest = ref({})

// 审核对话框相关
const reviewDialogVisible = ref(false)
const reviewType = ref('approve') // 'approve' 或 'reject'
const reviewFormRef = ref()
const reviewForm = ref({
  review_comments: ''
})
const reviewTarget = ref(null)

// 根据搜索条件过滤下载请求
const filteredRequests = computed(() => {
  let result = requests.value
  
  // 根据申请人过滤
  if (searchForm.value.applicant) {
    const name = searchForm.value.applicant
    result = result.filter(req => req.applicant && req.applicant.includes(name))
  }
  
  // 根据请求状态过滤
  if (searchForm.value.request_status) {
    result = result.filter(req => req.request_status === searchForm.value.request_status)
  }
  
  // 根据日期范围过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = new Date(dateRange.value[0])
    const endDate = new Date(dateRange.value[1])
    endDate.setHours(23, 59, 59, 999)
    
    result = result.filter(req => {
      const applyDate = new Date(req.request_time)
      return applyDate >= startDate && applyDate <= endDate
    })
  }
  
  // 按申请时间倒序排序
  result.sort((a, b) => new Date(b.request_time) - new Date(a.request_time))
  
  return result
})

// 分页下载请求
const paginatedRequests = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredRequests.value.slice(start, end)
})

// 获取数据
const getData = async () => {
  loading.value = true
  try {
    // 获取下载请求列表
    const data = await downloadAPI.getRequests()
    requests.value = data
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    applicant: '',
    request_status: ''
  }
  dateRange.value = []
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 查看请求详情
const viewRequestDetail = (requestId) => {
  const request = requests.value.find(req => req.request_id === requestId)
  if (request) {
    currentRequest.value = { ...request }
    detailDialogVisible.value = true
  }
}

// 显示批准对话框
const approveRequest = (row) => {
  reviewType.value = 'approve'
  reviewTarget.value = row
  reviewForm.value = {
    review_comments: ''
  }
  reviewDialogVisible.value = true
}

// 显示拒绝对话框
const rejectRequest = (row) => {
  reviewType.value = 'reject'
  reviewTarget.value = row
  reviewForm.value = {
    review_comments: ''
  }
  reviewDialogVisible.value = true
}

// 提交审核
const submitReview = async () => {
  try {
    const updatedRequest = {
      ...reviewTarget.value,
      request_status: reviewType.value === 'approve' ? '已批准' : '已拒绝',
      review_comments: reviewForm.value.review_comments,
      reviewer: localStorage.getItem('userName') || '管理员',
      review_time: new Date().toISOString()
    }
    
    await downloadAPI.updateRequest(updatedRequest) 
    ElMessage.success(`${reviewType.value === 'approve' ? '批准' : '拒绝'}请求成功`)
    
    reviewDialogVisible.value = false
    getData() // 重新获取数据
    
    // 如果批准了请求，可以在这里添加发送通知或生成下载链接的逻辑
    if (reviewType.value === 'approve') {
      ElMessage.info('已生成下载链接并通知用户')
    }
  } catch (error) {
    ElMessage.error('操作失败，请重试')
    console.error('审核请求失败:', error)
  }
}

// 根据状态获取标签类型
const getStatusType = (status) => {
  switch (status) {
    case '待审核':
      return 'warning'
    case '已批准':
      return 'success'
    case '已拒绝':
      return 'danger'
    default:
      return 'info'
  }
}

// 格式化请求内容显示
const formatRequestContent = (content) => {
  try {
    // 如果内容是JSON字符串，尝试解析
    const parsed = typeof content === 'string' ? JSON.parse(content) : content
    if (typeof parsed === 'object') {
      // 返回一个简洁的描述
      if (parsed.dataType) {
        return `数据类型: ${parsed.dataType}${parsed.timeRange ? `, 时间范围: ${parsed.timeRange}` : ''}`
      }
    }
  } catch (e) {
    // 如果解析失败，返回原始内容
  }
  return truncateText(content, 50)
}

// 文本截断
const truncateText = (text, length) => {
  if (!text) return ''
  return text.length > length ? text.substring(0, length) + '...' : text
}

// 组件挂载时获取数据
onMounted(() => {
  getData()
})
</script>

<style scoped>
.download-requests-container {
  padding: 20px;
  background-color: #1a1a1a;
  min-height: 100vh;
}

.page-card {
  margin-bottom: 20px;
  background-color: #2c2c2c;
  border-radius: 8px;
  border: 1px solid #404040;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #000000;
}

/* 确保标题文字为黑色 */
.card-header span {
  color: #000000 !important;
}

.search-filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #3a3a3a;
  border-radius: 4px;
  border: 1px solid #404040;
}

.search-form {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.request-content {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.request-content:hover {
  color: #66b1ff;
}

.reason-text {
  color: #d0d0d0;
  font-size: 14px;
}

.detail-content {
  white-space: pre-wrap;
  word-break: break-all;
}

/* 适配Element Plus深色主题下的组件 */
:deep(.el-input__wrapper),
:deep(.el-select__wrapper),
:deep(.el-date-editor .el-input__wrapper) {
  background-color: #3a3a3a !important;
  border-color: #555 !important;
  color: #ffffff;
}

:deep(.el-input__placeholder),
:deep(.el-select__placeholder) {
  color: #888 !important;
}

:deep(.el-input__inner),
:deep(.el-select__input) {
  color: #ffffff !important;
}

:deep(.el-input__wrapper:hover),
:deep(.el-select__wrapper:hover),
:deep(.el-date-editor .el-input__wrapper:hover) {
  border-color: #666 !important;
}

:deep(.el-input__wrapper.is-focus),
:deep(.el-select__wrapper.is-focus),
:deep(.el-date-editor .el-input__wrapper.is-focus) {
  border-color: #409eff !important;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) !important;
}

/* 表格样式 */
:deep(.el-table) {
  background-color: #2c2c2c;
  color: #ffffff;
}

:deep(.el-table__header-wrapper th) {
  background-color: #3a3a3a;
  color: #ffffff;
  border-bottom: 1px solid #404040;
}

:deep(.el-table__row) {
  border-bottom: 1px solid #404040;
}

:deep(.el-table__row:hover) {
  background-color: #3a3a3a;
}

/* 按钮样式 */
:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

:deep(.el-button--default) {
  background-color: #3a3a3a;
  border-color: #555;
  color: #ffffff;
}

:deep(.el-button--default:hover) {
  background-color: #4a4a4a;
  border-color: #666;
  color: #ffffff;
}

/* 对话框样式 */
:deep(.el-dialog__wrapper .el-dialog) {
  background-color: #2c2c2c;
  border: 1px solid #404040;
}

:deep(.el-dialog__wrapper .el-dialog__header) {
  border-bottom: 1px solid #404040;
}

:deep(.el-dialog__wrapper .el-dialog__title) {
  color: #ffffff;
}

:deep(.el-dialog__wrapper .el-form-item__label) {
  color: #ffffff;
}

:deep(.el-descriptions-item__label) {
  color: #ffffff !important;
  font-weight: normal !important;
}

:deep(.el-descriptions-item__content) {
  color: #ffffff !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
  }
}
</style>